package com.yxzx.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yxzx.api.entity.Course;
import com.yxzx.api.entity.CourseOrder;
import com.yxzx.api.entity.User;
import com.yxzx.api.exception.CustomException;
import com.yxzx.api.service.ICourseOrderService;
import com.yxzx.api.service.ICourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

import static com.yxzx.api.dto.RestStatusCode.COURSE_ORDER_ERROR;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author YWB
 * @since 2020-09-06
 */
@RestController
@RequestMapping("/api/course-order")
public class CourseOrderController extends BaseController{

    @Autowired
    private ICourseService courseService;

    @Autowired
    private ICourseOrderService orderService;



    @PostMapping("/{courseId}")
    @PreAuthorize("hasAuthority('ROLE_USER')")
    public ResponseEntity<CourseOrder> buyCourse(@PathVariable(value = "courseId") Long courseId){

        User user=getUser();

        if(user==null){
            return ResponseEntity.badRequest().build();
        }

        try{
            Course course = courseService.getById(courseId);
            if(course!=null){

                CourseOrder courseOrder = new CourseOrder();
                courseOrder.setCourseId(course.getId());
                courseOrder.setUserId(user.getId());

                //先查询是否已有订单
                QueryWrapper<CourseOrder> queryWrapper = new QueryWrapper<>();

                queryWrapper.setEntity(courseOrder);

                List<CourseOrder> orders = orderService.list(queryWrapper);
                if(!orders.isEmpty()){
                    return ResponseEntity.ok(orders.get(0));
                }


                courseOrder.setCourseTiltle(course.getTitle());
                courseOrder.setCreateTime(course.getCreateTime());
                courseOrder.setOrderStatus(2);
                courseOrder.setPayPrice(course.getPrice());
                courseOrder.setOrderTime(LocalDateTime.now());
                courseOrder.setPayTime(LocalDateTime.now());

                orderService.save(courseOrder);

                //更新课程购买人数
                courseService.updateSaleCount(courseId);


                return ResponseEntity.ok(courseOrder);
            }else {
                throw new CustomException(courseId+"",COURSE_ORDER_ERROR.getCode(),COURSE_ORDER_ERROR.getMessage());
            }

        }catch(Exception e){
            e.printStackTrace();
            throw new CustomException(courseId+"",COURSE_ORDER_ERROR.getCode(),COURSE_ORDER_ERROR.getMessage());

        }
    }






}
